package com.ymt.bpm.service.engine.bpd.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.dao.MDao;
import com.ymt.bpm.model.PBpdRef;
import com.ymt.bpm.service.engine.bpd.BpdRefService;
import com.ymt.bpm.util.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Johnny on 2017/4/11.
 */
@Service
public class BpdRefServiceImpl implements BpdRefService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private String mapper = "PBpdRefMapper";

    @Autowired
    private MDao dao;

    @Override
    public int saveRefs(String tenantId, String bpdId, String versionid, String bpmn, String otherConfig) {
        int rs = 0;
        //delete existing
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put(Const.TENANT_ID, tenantId);
        paramMap.put("bpdId", bpdId);
        paramMap.put("versionid", versionid);
        rs += dao.delete(mapper, "deleteByBpdIdVerId", paramMap);

        //insert news
        List<PBpdRef> refs = parseRefs(tenantId, bpdId, versionid, bpmn, otherConfig);
        if (refs!=null && refs.size()>0) {
            rs += dao.batchInsert(mapper, "insertSelective", refs);
        }
        return rs;
    }

    @Override
    public List<PBpdRef> parseRefs(String tenantId, String bpdId, String versionid, String bpmn, String otherConfig) {
        return null;
    }

    @Override
    public JSONArray referencedBy(String tenantId, String bpdId, String versionid) {
        PBpdRef obj = new PBpdRef();
        obj.setRefType("BPD");
        obj.setRefKey(bpdId);
        obj.setRefKey1(versionid);
        obj.setValid("1");
        List<Map<String, Object>> refs = dao.selectObjListByObj(mapper, "selectByObj", obj);
        if (refs!=null && refs.size()>0) {
            JSONArray rtn = new JSONArray();
            for (Map<String, Object> ref : refs) {
                JSONObject r = new JSONObject();
                if (!"BPD".equals(ref.get("ACTIVITY_ID"))) {
                    r.put("activityId", ref.get("ACTIVITY_ID"));
                    r.put("activityName", ref.get("ACTIVITY_NAME"));
                }
                r.put("bpdId", ref.get("BPD_ID"));
                r.put("bpdName", ref.get("BPD_NAME"));
                rtn.add(r);
            }
            return rtn;
        }
        return null;
    }
}
